package com.qing.seckill.scheduled;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qing.seckill.entity.TbSeckillGoods;
import com.qing.seckill.mapper.TbSeckillGoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@EnableScheduling
public class SeckillGoodsToRedisTask {

	@Autowired
	private TbSeckillGoodsMapper seckillGoodsMapper;


	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 每年双十一启动秒杀
	 * 将商品数据全部更新到索引库里
	 */
	@Scheduled(cron = "20 * * * * ?")   //测试数据没30秒执行
	public void startSeckill() {
		//查询储存数量大于0，活动开始时间小于现在，结束时间大于现在的商品添加到Redis缓存中
		QueryWrapper<TbSeckillGoods> queryWrapper = new QueryWrapper<>();
		queryWrapper.gt("stock_count", 0);
		queryWrapper.lt("start_time", LocalDateTime.now());
		queryWrapper.gt("end_time", LocalDateTime.now());
		List<TbSeckillGoods> goodsList = seckillGoodsMapper.selectList(queryWrapper);
		for (TbSeckillGoods tbSeckillGoods : goodsList) {
			redisTemplate.boundHashOps(TbSeckillGoods.class.getSimpleName()).put(String.valueOf(tbSeckillGoods.getId()), JSON.toJSON(tbSeckillGoods).toString());

			//给每个商品加入到Redis队列中，秒杀对应商品有多少个，则加多少个ID到队列中
			pushSeckillGoods(tbSeckillGoods);

		}


	}

	/**
	 * 给每个商品加入到Redis队列中
	 * 秒杀对应商品有多少个，则加入多少个ID到队列中
	 *
	 * @param goods
	 */
	private void pushSeckillGoods(TbSeckillGoods goods) {
		//库存量
		Integer stockCount = goods.getStockCount();
		Long size = redisTemplate.boundListOps(SysContant.SECKILL_PREFIX + goods.getId()).size();
		if (size == 0) {
			//循环加入Redis队列
			//左压栈方式加入
			for (Integer i = 0; i < stockCount; i++) {
				redisTemplate.boundListOps(SysContant.SECKILL_PREFIX + goods.getId()).leftPush(String.valueOf(goods.getId()));
			}
		}

	}
}
